/*******************************************************************************************
Copyright (C) 2014 Mestrelab Research S.L. All rights reserved.

This file is part of the Mnova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*******************************************************************************************/

/*globals settings, Dir, FileDialog, File, TextStream, Application, NMRSpectrum, print, Peak, MnUi*/
/*jslint plusplus: true, indent: 4*/

function exportFitRegions() {
	"use strict";

	function fitRegionToStream(aFitRegion, aFileStream, aNMRPeaks) {
		aFileStream.writeln("Name:\t", aFitRegion.name);
		aFileStream.writeln("From:\t", aFitRegion.from);
		aFileStream.writeln("To:\t", aFitRegion.to);
		aFileStream.writeln("Peaks:");
		aFileStream.writeln("shift\theight\twidth\tL/G\tArea");
		var p, peak,
			fitPeaksIds = aFitRegion.peaks;
		for (p = 0; p < fitPeaksIds.length; p++) {
			peak = new Peak(aNMRPeaks.byId(fitPeaksIds[p]));
			aFileStream.write(peak.delta(1), "\t", peak.intensity, "\t", peak.width(1), "\t", peak.kurtosis, "\t", peak.integral, "\n");
		}
		aFileStream.writeln();
	}

    var fout, sout, spc, peakList, fitRegions, fr, oldCurSpecIndex, i,
		dirSettingsKey = "exportFitRegions/LastDir",
		saveDir = settings.value(dirSettingsKey, Dir.home()),
		dw = Application.mainWindow.activeDocument,
		spectra = dw.itemCount("NMR Spectrum"),
		specIndex = 0,
		fileName = FileDialog.getSaveFileName("ASCII Files (*.txt)", "", saveDir);

    if (!fileName.length) {
		return;
	}

    fout = new File(fileName);
    settings.setValue(dirSettingsKey, fout.absDirPath);
    if (!fout.open(File.WriteOnly)) {
		throw "Impossible to open file";
	}
    sout = new TextStream(fout);
    sout.precision = 10;

    while (specIndex < spectra) {
		spc = new NMRSpectrum(dw.item(specIndex, "NMR Spectrum"));
		specIndex++;
		if (!spc.isValid()) {
			throw "Invalid Spectrum";
		}
		oldCurSpecIndex = spc.curSpecIndex;
		for (i = 0; i < spc.specCount; i++) {
			spc.curSpecIndex = i;
			peakList = spc.peaks();
			fitRegions = spc.fitRegions();
			print(fitRegions);
			for (fr = 0; fr < fitRegions.length; fr++) {
				fitRegionToStream(fitRegions[fr], sout, peakList);
			}
		}
		spc.curSpecIndex = oldCurSpecIndex;
    }
    fout.close();
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_ExportASCIIFitRegions = exportFitRegions;
}
